package org.zhang.core.track;

import java.util.UUID;

/**
 * 调用链上下文对象
 *
 * @author tameti
 */
public class CallContext {
    private static CallSpanThreadLocal<CallSpan> context = new CallSpanThreadLocal<>();
    private static CallSpanThreadLocal<String> traceContext = new CallSpanThreadLocal<>();

    public static Span createEntrySpan() {
        CallSpan callSpan = context.get();
        if (callSpan == null) {
            //先初始化层级
            callSpan = new CallSpan();
            context.set(callSpan);
        }
        return callSpan.createEntrySpan();
    }

    public static void exitSpan() {
        CallSpan callSpan = context.get();
        if (callSpan != null) {
            callSpan.exitSpan();
        }
    }

    public static void removeSpan() {
        CallSpan callSpan = context.get();
        if (callSpan != null) {
            context.remove();
        }
    }

    public static void removeTrace() {
        String trace = traceContext.get();
        if (trace != null && !trace.isEmpty()) {
            traceContext.remove();
        }
    }

    public static Span getCurrentSpan() {
        CallSpan callSpan = context.get();
        if (callSpan == null) {
            return null;
        }
        return callSpan.getCurrentSpan();
    }

    public static void setTrace() {
        String trace = traceContext.get();
        if (trace == null) {
            traceContext.set(UUID.randomUUID() + "");
        }
    }

    public static String getTrace() {
        return traceContext.get();
    }
}
